import React, { useState, useEffect } from "react";
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Row,
  Col,
  TreeSelect,
  Select,
  Spin,
} from "antd";
import { addField, upadataField, cmsSiteTree, getDetail } from "../api";
import { getSysDeptTreelist } from "../../../UserList/api";
import {
  sysDeptAllTree,
  cmsSiteAllTree,
  cmsColumnAllTree,
} from "../../column/api";
import styles from "../index.less";

const { SHOW_ALL } = TreeSelect;

/**
 * @zh-CN 部门同步树
 *
 * @param datas
 */

const setTreeFormat = (datas) => {
  const newData = [];

  datas.map((item) => {
    const obj = {
      id: item.deptId,
      value: item.deptId,
      pId: item.parentId,
      title: item.deptName,
    };
    if (item.children && item.children.length) {
      obj.children = setTreeFormat(item.children);
    }
    newData.push(obj);
    return "";
  });
  return newData;
};
/**
 * @zh-CN 站点同步树
 *
 * @param datas
 */

const setSiteTreeFormat = (datas) => {
  const newData = [];
  datas.map((item) => {
    const obj = {
      id: item.siteId,
      value: item.siteId,
      pId: item.parentId,
      title: item.siteName,
    };
    if (item.children && item.children.length) {
      obj.children = setSiteTreeFormat(item.children);
    }
    newData.push(obj);
    return "";
  });
  return newData;
};
/**
 * @zh-CN 栏目同步树格式化
 *
 * @param datas
 */

const setColumnTreeFormat = (datas) => {
  const newData = [];
  datas.map((item) => {
    const obj = {
      id: item.columnId,
      value: item.columnId,
      pId: item.parentId,
      title: item.columnName,
    };
    if (item.children && item.children.length) {
      obj.children = setColumnTreeFormat(item.children);
    }
    newData.push(obj);
    return "";
  });
  return newData;
};
const UpdateForm = (props) => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, currentIndex = 0 } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [dept, setDept] = useState(); //  部门
  const [site, setSite] = useState(); //  站点
  // const [column, setColumn] = useState(); //  栏目

  const [sysDeptAllTreeData, setSysDeptAllTreeData] = useState(); // 部门同步树
  const [cmsSiteAllTreeData, setcmsSiteAllTreeData] = useState(); // 站点同步树
  // const [cmsColumnAllTreeData, setcmsColumnAllTreeData] = useState(); // 栏目同步树

  // 详情
  const getDetailData = () => {
    setLoading(true);
    getDetail(data.siteId).then((res) => {
      setLoading(false);
      if (res.code === 0) {
        const siteUrl = data.siteUrl
          .replace(/http:\/\//, "")
          .replace(/https:\/\//, "");
        setSite(data.parentId === 0 ? [] : data.parentId);
        setDept(data.deptId);

        form.setFieldsValue({ ...data, siteUrl });
      } else {
        message.error(res.msg || "获取详情失败");
      }
    });
  };

  const httpSelector = (
    <Form.Item name="https" noStyle>
      <Select style={{ width: 90 }}>
        <Option value="http">http://</Option>
        <Option value="https">https://</Option>
      </Select>
    </Form.Item>
  );
  // const comTypeSelector = (
  //   <Form.Item name="com" noStyle>
  //     <Select style={{ width: 80 }}>
  //       <Option value="com">com</Option>
  //       <Option value="cn">cn</Option>
  //       <Option value="org.cn">org.cn</Option>
  //       <Option value="org">org</Option>
  //     </Select>
  //   </Form.Item>
  // );
  /**
   * @zh-CN 同步获取部门树
   *
   * @param fields
   */
  const getSysDeptAllTree = async (fields) => {
    try {
      const data = await sysDeptAllTree({ ...fields });
      if (data.code === 0) {
        setSysDeptAllTreeData(setTreeFormat([data.data]));
        return;
      }
    } catch (error) {
      message.error("获取部门失败，请重试");
      return false;
    }
  };

  /**
   * @zh-CN 同步获取站点树
   *
   * @param fields
   */
  const getCmsSiteAllTree = async (fields) => {
    try {
      const data = await cmsSiteAllTree({ ...fields });
      if (data.code === 0) {
        setcmsSiteAllTreeData(setSiteTreeFormat([data.data]));
        return;
      }
    } catch (error) {
      message.error("获取站点失败，请重试");
      return false;
    }
  };

  /**
   * @zh-CN 同步获取栏目树
   *
   * @param fields
   */
  // const getcmsColumnAllTree = async fields => {
  //   try {
  //     const data = await cmsColumnAllTree({ ...fields });
  //     if (data.code === 0) {
  //       setcmsColumnAllTreeData(setColumnTreeFormat(data.data));
  //       return;
  //     }
  //   } catch (error) {
  //     message.error('获取站点失败，请重试');
  //     return false;
  //   }
  // };

  // 选择部门
  const deptOnChange = (value) => {
    setDept(value);
  };
  // 选择站点
  const siteOnChange = (value) => {
    setSite(value);
  };
  // const columnOnChange = value => {
  //   setColumn(value);
  // };

  useEffect(() => {
    if (!sysDeptAllTreeData && visible) {
      getSysDeptAllTree();
    }
    if (!cmsSiteAllTreeData && visible) {
      getCmsSiteAllTree();
    }
    // if (!cmsColumnAllTreeData && visible) {
    //   getcmsColumnAllTree();
    // }
    if (type === "updata" && visible === true) {
      getDetailData();
    } else {
      form.resetFields();
    }

    form.setFieldsValue({ status: 0, orderNum: currentIndex, https: "http" });
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = (values) => {
    const hide = message.loading("正在添加");
    setLoading(true);
    upadataField({
      ...values,
      siteId: data.siteId,
      parentId: site,
      deptId: dept,
      // columnId: column,
    }).then((res) => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        modelClose(false);
        onSuccess();
      } else {
        message.error(res.msg || "修改失败，请重试");
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = (values) => {
    const hide = message.loading("正在添加");
    setLoading(true);

    addField({ ...values, parentId: site, deptId: dept }).then((res) => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        modelClose(false);
        onSuccess();
      } else {
        message.error(res.msg || "添加失败，请重试");
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then((values) => {
      if (!dept) {
        message.error("部门不能为空");
        return;
      }

      values.siteUrl = `${values.https}://${values.siteUrl}`;
      // if (!column) {
      //   message.error('栏目不能为空');
      //   return;
      // }
      if (type === "updata") updataData(values);
      if (type === "add") addData(values);
    });
  };

  const modelClose = () => {
    setDept();
    setSite();
    // setColumn();
    onCancel(false);
  };

  return (
    <>
      <Drawer
        getContainer={false}
        width={640}
        title={type === "updata" ? "修改" : "添加"}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: "right",
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button
              onClick={sendData}
              type="primary"
              loading={loading}
              disabled={loading}
            >
              保存
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <Form {...formItemLayout} name="control-ref" form={form}>
            {visible && (
              <div className={styles.treeBox}>
                <Row>
                  <Col span={14} push={4}>
                    <TreeSelect
                      treeData={sysDeptAllTreeData}
                      placeholder="选择部门"
                      value={dept}
                      style={{ width: 340 }}
                      allowClear
                      // multiple
                      showSearch
                      // treeDefaultExpandAll
                      onChange={(value, label, extra) => {
                        deptOnChange(value, label, extra);
                      }}
                    />
                  </Col>
                  <Col span={4} pull={14}>
                    <div className={styles.treeName}>
                      <em className="star">*</em>选择部门：
                    </div>
                  </Col>
                </Row>
              </div>
            )}
            {visible && (
              <div className={styles.treeBox}>
                <Row>
                  <Col span={14} push={4}>
                    <TreeSelect
                      treeData={cmsSiteAllTreeData}
                      placeholder="父级站点"
                      value={site}
                      style={{ width: 340 }}
                      // multiple
                      showSearch
                      // treeDefaultExpandAll
                      onChange={(value, label, extra) => {
                        siteOnChange(value, label, extra);
                      }}
                      allowClear
                    />
                  </Col>
                  <Col span={4} pull={14}>
                    <div className={styles.treeName}>父级站点：</div>
                  </Col>
                </Row>
              </div>
            )}

            <Form.Item
              label="站点名称"
              name="siteName"
              rules={[{ required: true }]}
            >
              <Input maxLength={20} allowClear />
            </Form.Item>
            {/* {visible && (
            <div className={styles.treeBox}>
              <Row>
                <Col span={14} push={4}>
                  <TreeSelect
                    treeData={cmsColumnAllTreeData}
                    placeholder="选择栏目"
                    value={column}
                    style={{ width: 340 }}
                    multiple
                    showSearch
                    treeCheckable={true}
                    showCheckedStrategy={SHOW_ALL}
                    onChange={(value, label, extra) => {
                      columnOnChange(value, label, extra);
                    }}
                    allowClear
                  />
                </Col>
                <Col span={4} pull={14}>
                  <div className={styles.treeName}>
                    <em className="star">*</em>选择栏目：
                  </div>
                </Col>
              </Row>
            </div>
          )} */}
            <Form.Item label="描述" name="description">
              <Input.TextArea maxLength={200} allowClear />
            </Form.Item>
            <Form.Item
              label="站点Url"
              rules={[{ required: true }]}
              name="siteUrl"
            >
              <Input
                maxLength={100}
                addonBefore={httpSelector}
                // addonAfter={comTypeSelector}
                allowClear
                placeholder="例如：www.baidu.com"
              />
            </Form.Item>
            <Form.Item width="xs" name="orderNum" label="显示顺序">
              <InputNumber min={0} max={1000} />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Radio.Group>
                <Radio value={0}>正常</Radio>
                <Radio value={1}>停用</Radio>
              </Radio.Group>
            </Form.Item>
          </Form>
        </Spin>
      </Drawer>
    </>
  );
};

export default UpdateForm;
